package demo_wty.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author:wangtianyu(王天宇)
 * @Date：Created on 2020/3/27 0027 21:32
 * @Description:
 * 处理请求参数：
 * 参数的请求方式：
 * 1、queryString请求：一般在url的后面 形如http://localhost:8080/user?name=wty&age=21
 * 可以通过req.getParameter("name")的方式来获取数据
 * ?name=wty&age=21 分解为K-V型 name => wty  age => 21
 *
 * 2、application/x-www-form-urlencoded：不会显示的绑定在url地址后面
 *
 * 3、application/json：
 * 不可以通过req.getParameter("name")的方式来获取数据
 * 要在 ServletInputStream 里面获取
 */
@WebServlet("/user")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("GET");
//        String name = req.getParameter("name");
//        String age = req.getParameter("age"); // 获取的参数都是String类型
//        System.out.println(String.format("%s => %s",name,age));

        // application/json
        System.out.println(req.getContentType());
        ServletInputStream inputStream = req.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";
        StringBuilder value = new StringBuilder("");
        while ((line = bufferedReader.readLine()) != null){
//            System.out.println(line);
            value.append(line);
        }
        //通过fastJson进行WtyUser的封装
        WtyUser wtyUser = JSON.parseObject(value.toString(), WtyUser.class);
        System.out.println(wtyUser);

        //封装成map
        JSONObject jsonObject = JSON.parseObject(value.toString());
        System.out.println(jsonObject.get("name"));
        System.out.println(jsonObject.get("age"));
        bufferedReader.close();
        inputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("POST"); // 获取参数和请求方式无关
        String name = req.getParameter("name");
        String age = req.getParameter("age"); // 获取的参数都是String类型
        System.out.println(String.format("%s => %s",name,age));
    }
}
